import time
import requests
import os.path
import json
from stats import Stats

class StatRequestor:
	engine = "http://api.flurry.com/"
	service = None
	metric = None
	params = None
	cache_file_name = None

	def __init__(self, service, metric, params):
		self.service = service
		self.metric = metric
		self.params = params

		file_name = self.service + self.metric + "_" + self.params["startDate"] + "_" + self.params["apiKey"] + ".json"
		file_name = file_name.replace("/", "_")
		self.cache_file_name = "cache/" + file_name

	def get_stats(self):
		cache_data = self.get_cache()
		if cache_data:
			stats = Stats(cache_data['@metric'], cache_data['@startDate'], cache_data['@endDate'], cache_data['@generatedDate'])

			stats.set_days(cache_data)

			return stats
		else:
			time.sleep(1.100)

			r = requests.get(self.engine + self.service + self.metric, params=self.params)
			result = r.json()
			
			f = open(self.cache_file_name, "w")
			json.dump(result, f)

			stats = Stats(result['@metric'], result['@startDate'], result['@endDate'], result['@generatedDate'])

			stats.set_days(result)

			return stats

	def get_cache(self):
		if os.path.isfile(self.cache_file_name):
			f = open(self.cache_file_name, "r")
			json_data = json.load(f)

			return json_data
		else:
			return None

	def __str__(self):
		return "StatRequestor (%s, %s, %s, %s)" % (self.engine, self.service, self.metric, self.params)

if __name__ == "__main__":
#	p = {'apiAccessCode' : APIACCESSCODE', 'apiKey' : "Z4G89SJVYJ762BNCPJBC", 'startDate' : "2013-09-23", 'endDate' : "2013-12-24"}
	
	requestor = StatRequestor("appMetrics/", "Sessions", p)

	print(requestor)

	requestor.get_stats()

	print 
